/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isValidBST(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
       int lastVal = 0;
       int cnt = 0;

       return isValidBST(root, lastVal, cnt);
    }

    bool isValidBST(TreeNode *root, int &lastVal, int &cnt) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (root == NULL) {
          return true;
        }
        if (root->left) {
          if (!isValidBST(root->left, lastVal, cnt)) {
            return false;
          }
        }
        if (cnt > 0) {
          if (root->val <= lastVal) {
            return false;
          }

        }
        ++cnt;
        lastVal = root->val;

        if (root->right) {
          if (!isValidBST(root->right, lastVal, cnt)) {
            return false;
          }
        }
        return true;
    }
};
